import hashlib

import jwt
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from core.crud import user_detail_by_username
from core.dependencies import get_db, log_route, common_dependencies_no_auth, log_route_no_auth
from core.schemas import UserLogin, ResponseModel

router = APIRouter(
    prefix="/auth",
    tags=["认证"],
    responses={404: {"description": "Not found"}},
)


@router.post("/login")
async def login(user_login: UserLogin, db: Session = Depends(get_db), common: dict = Depends(common_dependencies_no_auth), _=Depends(log_route_no_auth)):
    user = user_detail_by_username(db, user_login.username)
    if not user:
        return ResponseModel(data=None, code="404", message="User does not exist")
    if hashlib.md5(user_login.password.encode()).hexdigest() != user.password:
        return ResponseModel(data=None, code="401", message="Password error")

    payload = {
        "user_id": user.user_id,
        "username": user.username  # Add the username to the JWT token
    }
    return ResponseModel(data={"token": jwt.encode(payload, "demo-key", algorithm="HS256")}, code="200",
                         message="success")